package xin.zhiyin.控制.登录;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xin.zhiyin.实体.DTO.用户DTO;
import xin.zhiyin.实体.DTO.登录状态;
import xin.zhiyin.实体.用户Entity;
import xin.zhiyin.工具.JthinkConstant;
import xin.zhiyin.工具.ResponseBo;
import xin.zhiyin.工具.captcha.HappyCaptcha;
import xin.zhiyin.服务.用户Service;
import xin.zhiyin.配置.ValidateCodeException;
import xin.zhiyin.配置.cache.JthinkCache;

@Controller
@RequestMapping(path = "/login")//页面的url地址
public class 登录 {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private 用户Service 用户Service;
    private JthinkCache jthinkCache;
    @GetMapping(path = "")
    public String 登录页(Model model){
        model.addAttribute("captchaType","math");
        return "login/login";
    }
    @RequestMapping(path = "/check")
    @ResponseBody
    public 登录状态 登录核验(用户DTO 用户dto, HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
        boolean flag = HappyCaptcha.verification(request,用户dto.getLoginCaptcha(),true);  /*第三个参数为true:忽略大小写字母;第三个参数为false:强校验大小写字母则设置为false。*/
        用户Entity user= 用户Service.根据登录名称和登录密码查询用户(用户dto.getLoginName(),用户dto.getLoginPassword());
        登录状态 denglu = new 登录状态();
        if(null != user && flag == true)
        {
            log.info(user.getLoginName() + "登录成功");
            StpUtil.login(user.getId());
            user.setLoginPassword(null);
            StpUtil.getSession().set("user", user);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            System.out.println("t++++++++++++++++++++"+tokenInfo);
            denglu.setResult("success");
            HappyCaptcha.remove(request);  /*将Session中存放的验证码清理掉*/
        }else if(user != null && flag == false){
            denglu.setResult("captchaerror");
        }else{
            denglu.setResult("usererror");
        }
        return denglu;
    }
    @GetMapping("/remove")
    public String logout(){
        StpUtil.logout();
        return "redirect:/login";
    }
}
